package com.glsc.ngateway.opmanage.service.report.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.excel.GltbFundStatus;
import com.glsc.ngateway.common.base.repo.mysql.opmanage.report.excel.GltbFundStatusRepo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GltbFundStatusListener extends AnalysisEventListener<GltbFundStatus> {

    private static final int BATCH_COUNT = 3000;
    List<GltbFundStatus> list=new ArrayList<GltbFundStatus>();

    private GltbFundStatusRepo gltbFundStatusRepo;
    private String date;
    private Boolean isClear=false;

    public GltbFundStatusListener(){
    }

    public GltbFundStatusListener(GltbFundStatusRepo gltbFundStatusRepo){
        this.gltbFundStatusRepo=gltbFundStatusRepo;
    }

    @Override
    public void invoke(GltbFundStatus data, AnalysisContext analysisContext) {
        if(data.getFundName()!=null){
            if(!isClear){
                gltbFundStatusRepo.deleteByDate(data.getDate());
                isClear=true;
            }
            data.setNetAssets(data.getNetAssets().replace(",",""));
            data.setTotalAssets(data.getTotalAssets().replace(",",""));
            data.setTotalProfit(data.getTotalProfit().replace(",",""));
            list.add(data);
        }
        System.out.println("****"+data+ JSON.toJSONString(data));
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }

    }

    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
    }
    //读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData(){
        gltbFundStatusRepo.saveAll(list);
    }
}
